export class SocketServer{
    static instance = null;
    static get Instance(){
        if(!this.instance){
            this.instance = new SocketServer()
        }
        return this.instance
    }
    ws = null
    callbackMapping = {};
    connected = false;
    sendretryCount = 0;
    connectretryCount = 0;
    timer= null;
    connextion(){
        if(!window.WebSocket){
            console.log('你的电脑不支持websocket')
            return;
        }
        this.ws = new WebSocket('ws:localhost:8888')
        this.ws.onopen =()=>{
            this.connected = true;
            this.connectretryCount = 0
            console.log('服务器连接成功       '+this.connectretryCount*500);
        }
        this.ws.onclose =()=>{
            this.connected =false;
            this.connectretryCount++;
            setTimeout(()=>{
              this.connextion();
          },500*this.connectretryCount)
            // console.log('服务器关闭      '+this.connectretryCount*500);
        }
        this.ws.onerror = ()=>{
            console.log('服务器连接错误');
        }
        this.ws.onmessage =(msg)=>{
            const payload = JSON.parse(msg.data)
            const {action,socketType,data} = payload;
            if(action=='getData'){
               if(this.callbackMapping[socketType]){
                //    console.log(this.callbackMapping[socketType]); Seller里面getdata函数
                this.callbackMapping[socketType].call(this,JSON.parse(data))
               }
            }else if(action=='fullScreen'){

            }else{

            }
        }
    }
    registerCallback(socketType,callback){
        this.callbackMapping[socketType] = callback;
    }
    unregisterCallback(socketType){
        this.callbackMapping[socketType] = null;
    }
    send(data){
       if(this.connected){
           this.sendretryCount = 0;
        this.ws.send(JSON.stringify(data))
       }else{
           setTimeout(()=>{
               this.sendretryCount++;
               this.send(data)
               console.log('send发送次数'+this.sendretryCount*500)
           },500*this.sendretryCount)
       }
    }
}